package stackdemo;

import java.util.Arrays;

/**
 * Created with IntelliJ IDEA
 * Description: 栈的模拟实现
 * User: SEKI TOMOKI
 * Date: 2024-08-01
 * Time: 18:01
 */
public class MyStack implements IStack{
    private int[] elements;
    private int usedSize;
    private static final int DEFAULT_SIZE = 10;
    public MyStack() {
        elements = new int[DEFAULT_SIZE];
    }


    @Override
    public void push(int elem) {
        //如果这个栈已经满了需要扩容
        if(full()) {
            this.elements = Arrays.copyOf(this.elements, size()*2);
        }
        this.elements[size()] = elem;
        usedSize++;
    }

    @Override
    public int pop() {
        //如果这个栈没有数据,返回异常
        if(empty()) {
            throw new EmptyException("栈是空的");
        }
        //如果是引用数据类型,要把出栈的数据置空
        int ret = this.elements[--usedSize];
        return ret;
    }

    @Override
    public int peek() {
        //如果这个栈没有数据,返回异常
        if(empty()) {
            throw new EmptyException("栈是空的");
        }
        return this.elements[size() - 1];
    }

    @Override
    public int size() {
        return this.usedSize;
    }

    @Override
    public boolean empty() {
        return this.usedSize == 0;
    }

    @Override
    public boolean full() {
        return this.usedSize == this.elements.length;
    }
}
